import { API } from '../helpers/axios'

const getConversationsApi = async ({
  inboxId,
  status,
  assigneeType,
  page
}) => {
  return API.get(`/api/v1/accounts/d062bd4e-2646-7b63-a740-3a08abcc6608/conversations`, { params: {
    inboxId,
    status,
    assigneeType,
    page
  } })
}

const getPreviousMessagesApi = async ({ conversationId, before }) => {
  return API.get(`/api/v1/accounts/d062bd4e-2646-7b63-a740-3a08abcc6608/conversations/${conversationId}/messages`, { params: {
    before
  } })
}

const toggleTypingStatusApi = async ({ conversationId, typingStatus, isPrivate }) => {
  return API.post(`/api/v1/accounts/d062bd4e-2646-7b63-a740-3a08abcc6608/conversations/${conversationId}/toggleTypingStatus`, {
    typingStatus,
    isPrivate
  })
}

const messageApi = async ({
  conversationId,
  message,
  isPrivate,
  echoId,
  files,
  ccEmails = '',
  bccEmails = ''
}) => {
  return API.post(`/api/v1/accounts/d062bd4e-2646-7b63-a740-3a08abcc6608/conversations/${conversationId}/messages`, buildCreatePayload({
    message,
    isPrivate,
    echoId,
    files,
    ccEmails,
    bccEmails
  }))
}

export const buildCreatePayload = ({
  message,
  isPrivate,
  echoId,
  files = [],
  ccEmails = '',
  bccEmails = ''
}) => {
  let payload

  payload = new FormData()
  if (message) {
    payload.append('content', message)
  }
  files.forEach(file => {
    payload.append('attachments[]', file)
  })
  payload.append('private', isPrivate)
  payload.append('echoId', echoId)
  payload.append('ccEmails', ccEmails)
  payload.append('bccEmails', bccEmails)

  return payload
}

export {
  getConversationsApi,
  getPreviousMessagesApi,
  toggleTypingStatusApi,
  messageApi
}
